package com.kkd.kkdapp.base;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.AccountEverydayActivity;
import com.kkd.kkdapp.activity.CalendarActivity;
import com.kkd.kkdapp.activity.CreditorIsRightsParticularsActivity;
import com.kkd.kkdapp.activity.DebtExchangeActivity;
import com.kkd.kkdapp.activity.DebtSuccessActivity;
import com.kkd.kkdapp.activity.FinancialPlanParticularsActivity;
import com.kkd.kkdapp.activity.GestureEditActivity;
import com.kkd.kkdapp.activity.GestureVerifyActivity;
import com.kkd.kkdapp.activity.HomeActivity;
import com.kkd.kkdapp.activity.ImageZoomActivity;
import com.kkd.kkdapp.activity.InformationActivity;
import com.kkd.kkdapp.activity.KKDWebActivity;
import com.kkd.kkdapp.activity.LivePlayerActivity;
import com.kkd.kkdapp.activity.LoginActivity;
import com.kkd.kkdapp.activity.MyActivity;
import com.kkd.kkdapp.activity.MyDebtDetailActivity;
import com.kkd.kkdapp.activity.MyHeadPortraitActivity;
import com.kkd.kkdapp.activity.MyRegularDebtActivity;
import com.kkd.kkdapp.activity.NoticeDetailActivity;
import com.kkd.kkdapp.activity.PersonalInformationActivity;
import com.kkd.kkdapp.activity.RegularParticularsActivity;
import com.kkd.kkdapp.activity.TenderDetailActivity;
import com.kkd.kkdapp.activity.WeiboShareActivity;
import com.kkd.kkdapp.activity.WelcomeActivity;
import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.fragment.WalletFragment;
import com.kkd.kkdapp.http.entity.Share;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.patternlock.PatternLockUtils;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.share.AccessTokenKeeper;
import com.kkd.kkdapp.utils.share.SinaConstants;
import com.kkd.kkdapp.utils.share.ThreadManager;
import com.kkd.kkdapp.view.ShareView.ShareCallback;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UHandler;
import com.umeng.message.entity.UMessage;

/**
 * 
 * @ClassName: BaseActivity
 * 
 * 
 */
public class BaseActivity extends FragmentActivity implements
		IWeiboHandler.Response {
	private static final int SHARE_CODE_ZERO = 1;
	private static final int SHARE_CODE_ELSE = 2;
	public static boolean isNeedUpdateTime = true; // 是否更新后台运行起始时间

	protected SystemBarTintManager mTintManager;// 所有子Activity请统一使用该TintManager对象
	// public static DefineKeyboardUtil mDefineKeyboardUtil; //输入法管理类
	// public StockKeyboardView mStockKeyboardView;
	public int newMsgCount;

	// 手指上下滑动时的最小速度
	private static final int YSPEED_MIN = 1000;

	// 手指向右滑动时的最小距离
	private static int XDISTANCE_MIN;

	// 手指向上滑或下滑时的最小距离
	private static final int YDISTANCE_MIN = 100;

	// 记录手指按下时的横坐标。
	private float xDown;

	// 记录手指按下时的纵坐标。
	private float yDown;

	// 记录手指移动时的横坐标。
	private float xMove;

	// 记录手指移动时的纵坐标。
	private float yMove;

	// 用于计算手指滑动的速度。
	private VelocityTracker mVelocityTracker;
	private static int shareType = QQShare.SHARE_TO_QQ_TYPE_DEFAULT;
	private static Context context;
	public static int shareResult = -1; // 微信和新浪微博分享
	private Share shareData;
	private Dialog shareFailure; // 分享失败Dialog
	private Dialog happyCoinCompleteProgressDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SHARE_CODE_ZERO:
				LogUtil.e("TAG", "结果：" + System.currentTimeMillis());
				// 分享邀请好友获得快乐币个数
				int inviteCionSum = shareData.getInviteCionSum();
				// 0未完成，1完成；
				int inviteStatus = shareData.getInviteStatus();
				// 签到完成状态，0未完成，1完成；
				int signInStatus = shareData.getSignInStatus();
				// 签到获取快乐币个数
				int signInCionSum = shareData.getSignInCionSum();
				// 签到优惠券金额
				long signIncouponAmount = shareData.getSignIncouponAmount();
				// 连续签到天数
				int signDays = shareData.getDays();
				// 投资完成状态，0未完成，1完成；
				int poiStatus = shareData.getPoiStatus();
				// 投资奖励快乐币个数
				int poiCionSum = shareData.getPoiCionSum();
				// 投资任务未完成提示最高奖励快乐币个数
				int poiMoreCionSum = shareData.getPoiMoreCionSum();
				// true弹出，false不弹出
				boolean popUp = shareData.getPopUp();
				// 邀请好友攻略Url
				String inviteStrategyUrl = shareData.getInviteStrategyUrl();
				// 快乐币任务全部完成获取快乐币总数
				int doubleAllSum = shareData.getDoubleAllSum();
				// 完成快乐币任务排名
				int customerSeat = shareData.getCustomerSeat();
				// 完成任务获得快乐币个数
				int doubleSum = shareData.getDoubleSum();
				// 完成快乐币任务翻倍的倍率
				String doubleRate = shareData.getDoubleRate();
				// 翻倍获取快乐币个数
				int doubleMisSum = shareData.getDoubleMisSum();
				// 快乐币任务url
				String coinMisUrl = shareData.getCoinMisUrl();
				// 是否可以补签 0：不可以，1：可以
				int isRepairSigninStatus = shareData.getIsRepairSigninStatus();
				if (popUp) {
					happyCoinCompleteProgressDialog(signInStatus,
							signInCionSum, signIncouponAmount, signDays, 2,
							inviteCionSum, inviteStatus, poiStatus, poiCionSum,
							poiMoreCionSum, inviteStrategyUrl, doubleAllSum,
							customerSeat, doubleSum, doubleRate, doubleMisSum,
							coinMisUrl, isRepairSigninStatus);
				}
				break;
			case SHARE_CODE_ELSE:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BaseApplication.getInstance().addActivity(this);
		isNeedUpdateTime = true;
		mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
				SinaConstants.APP_KEY);
		mWeiboShareAPI.registerApp();
		try {
			initTintManager();
		} catch (Exception e) {
		}
		XDISTANCE_MIN = SystemUtils.dip2px(BaseActivity.this, 90);
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.enable();
		PushAgent.getInstance(this).onAppStart();
		UHandler notificationClickHandler = new UHandler() {

			@Override
			public void handleMessage(Context arg0, UMessage msg) {
				if (msg.after_open.endsWith("go_activity")) {
					if ("account".equals(msg.activity)) { // 天天赚转出成功
						Intent intent = new Intent(BaseActivity.this,
								HomeActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						HomeActivity.mActivity.walletNavigation();
						WalletFragment.mWalletFragment.requestAnimation();
					} else if ("yuebaoSell".equals(msg.activity)) { // 天天赚转出失败
						Intent intent_toEveryday = new Intent(
								BaseActivity.this,
								AccountEverydayActivity.class);
						startActivity(intent_toEveryday);
					} else if ("homepage".equals(msg.activity)) {
						Intent intent = new Intent(BaseActivity.this,
								HomeActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						HomeActivity.mActivity.homeNavigation();
					}
				} else if (msg.after_open.endsWith("go_url")) {
					if (!TextUtils.isEmpty(msg.url)) {
						Intent intent2 = new Intent(BaseActivity.this,
								KKDWebActivity.class);
						intent2.putExtra("url", msg.url);
						intent2.putExtra("shareUrl", "");
						startActivity(intent2);
					}
				} else {
					Intent intent = new Intent(BaseActivity.this,
							NoticeDetailActivity.class);
					Gson gson = new Gson();
					intent.putExtra("msg", gson.toJson(msg));
					startActivity(intent);
				}

			}
		};

		mPushAgent.setNotificationClickHandler(notificationClickHandler);
		if (savedInstanceState != null) {
			mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
		}
		BaseActivity.context = getApplicationContext();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		// 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
		// 来接收微博客户端返回的数据；执行成功，返回 true，并调用
		// {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
		mWeiboShareAPI.handleWeiboResponse(intent, this);
	}

	@TargetApi(19)
	public void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	/**
	 * 初始化为状态栏为纯黑色
	 */
	private void initTintManager() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		mTintManager = new SystemBarTintManager(this);
		mTintManager.setStatusBarTintEnabled(true);
		mTintManager.setNavigationBarTintEnabled(true);
		mTintManager.setStatusBarTintResource(R.color.blue_5451b1);
		// mTintManager.setTintColor(0x05FF0000);
	}

	@Override
	public Resources getResources() {
		Resources res = super.getResources();
		Configuration config = new Configuration();
		config.setToDefaults();
		res.updateConfiguration(config, res.getDisplayMetrics());
		return res;
	}

	public void gain() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		String strOpt = "手机分辨率为:" + dm.widthPixels + "X" + dm.heightPixels;
		LogUtil.e("strOpt---->", strOpt);
	}

	// // 获取当前应用版本号
	// public String getVersionName() throws Exception {
	// // 获取packagemanager的实例
	// PackageManager packageManager = getPackageManager();
	// // getPackageName()是你当前类的包名，0代表是获取版本信息
	// PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
	// 0);
	// String version = packInfo.versionName;
	// return version;
	// }

	// 获取当前应用版本号
	public int getVersionCode() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		int versionCode = packInfo.versionCode;
		return versionCode;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!(this instanceof KKDWebActivity)) {
			MobclickAgent.onResume(this);
		}
		TCAgent.onPageStart(this, getClass().getName());
		if (PreferenceUtils.getInstance().getLogin(this) == 0) {
			if (!(this instanceof WelcomeActivity)
					&& !(this instanceof LoginActivity)
					&& !(this instanceof MyHeadPortraitActivity)
					&& !(this instanceof PersonalInformationActivity)) {
				KkdAppInfo appinfo = KkdAppInfo.getKkdAppInfo();
				long curtime = System.currentTimeMillis() / 1000;
				if (appinfo == null
						|| ((curtime - appinfo.backgroundTime) > 5 * 60)) {
					isNeedUpdateTime = false;
					if (TextUtils.isEmpty(PreferenceUtils.getInstance()
							.getGesturePW(this))) {
						startActivity(new Intent(this,
								GestureEditActivity.class));
					} else {
						startActivityForResult(new Intent(this,
								GestureVerifyActivity.class), 600);
					}

					// try {
					// BaseApplication.getInstance().addActivity(this);
					// PatternLockUtils.confirmPatternIfHas(this);
					// // 是否必须验证通过
					// PreferenceUtils.getInstance().isMustRight = true;
					// } catch (Exception e) {
					// BaseApplication.getInstance().addActivity(this);
					// PreferenceUtils.getInstance().isMustRight = true;
					// }

				}

			}
		}

		if (shareResult == 0) { // 　微信和新浪微博分享成功
			if (PreferenceUtils.getInstance().getH5Entrance(this)
					.equals("邀请好友攻略")) {
				addCoinMis(); // 快乐币任务邀请好友
			} else if (PreferenceUtils.getInstance().getH5Entrance(this)
					.equals("视频分享")) {
				videoShareSuccess(); // 视频分享
			}
			PreferenceUtils.getInstance().setH5Entrance(this, "");
			shareResult = -1;
		} else if (shareResult == 1) { // 微信和新浪微博分享失败
			if (PreferenceUtils.getInstance().getH5Entrance(this)
					.equals("邀请好友攻略")) {
				shareFailureDialog();
			}
			PreferenceUtils.getInstance().setH5Entrance(this, "");
			shareResult = -1;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (!(this instanceof KKDWebActivity)) {
			MobclickAgent.onPause(this);
		}
		TCAgent.onPageEnd(this, getClass().getName());
		ImageLoader.getInstance().stop();
		if (isNeedUpdateTime) {
			KkdAppInfo appinfo = new KkdAppInfo();
			appinfo.backgroundTime = System.currentTimeMillis() / 1000;
			KkdAppInfo.insert(appinfo);
		}

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		if (!isAppOnForeground()) {
		}
	}

	public SsoHandler mSsoHandler;
	public WeiboAuthListener mWeiboAuthListener;

	public IWeiboShareAPI mWeiboShareAPI;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Constants.REQUEST_QQ_SHARE) {
			Tencent.onActivityResultData(requestCode, resultCode, data,
					qqShareListener);
		} else if (requestCode == Constants.REQUEST_QZONE_SHARE) {
			Tencent.onActivityResultData(requestCode, resultCode, data,
					qZoneShareListener);
		}
		if (requestCode == PatternLockUtils.REQUEST_CODE_CONFIRM_PATTERN) {
			if (resultCode != RESULT_OK
					&& PreferenceUtils.getInstance().isMustRight) {
				isNeedUpdateTime = false;
			}
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	/**
	 * 
	 * 程序是否在前台运行
	 * 
	 * @return
	 */
	public boolean isAppOnForeground() {

		ActivityManager activityManager = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	// 判断手机格式是否正确
	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((1[3,4,5,7,8][0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	// 过滤特殊字符
	public boolean userstringFilter(String str) throws PatternSyntaxException {
		String regEx = "[0-9a-zA-Z]{6,16}";
		return str.matches(regEx);
	}

	// 身份证验证
	public boolean isIdentity(String str) throws PatternSyntaxException {
		String regex = "([0-9]{17}([0-9]|X))|([0-9]{15})";
		return str.matches(regex);
	}

	// 正整数
	public boolean positiveInteger(String str) throws PatternSyntaxException {
		String regex = "^[0-9]*[1-9][0-9]*$";
		return str.matches(regex);
	}

	// 只能输入数字
	public boolean figure(String str) throws PatternSyntaxException {
		String regex = "^[0-9]*$";
		return str.matches(regex);
	}

	// 输入正整数、两位小数
	public boolean decimals(String str) throws PatternSyntaxException {
		String regex = "^?\\d*([.]\\d{0,2})?$";
		return str.matches(regex);
	}

	/**
	 * 判断银行卡号
	 */
	// Description: 银行卡号Luhm校验

	// Luhm校验规则：16位银行卡号（19位通用）:

	// 1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
	// 2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
	// 3.将加法和加上校验位能被 10 整除。

	// 开头6位
	// private final static String strBin =
	// "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";

	private final static String SUCCESS = "true";

	private final static String BAD_LENGTH = "银行卡号长度必须在16到19之间";

	private final static String NOT_NUMBER = "银行卡必须全部为数字";

	private final static String ILLEGAL_NUMBER = "您输入的银行卡号不合法";

	public static String luhmCheck(String bankno) {
		if (bankno.length() < 16 || bankno.length() > 19) {
			return BAD_LENGTH;
		}

		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher match = pattern.matcher(bankno);
		if (match.matches() == false) {
			return NOT_NUMBER;
		}

		// if (strBin.indexOf(bankno.substring(0, 2)) == -1) {
		// return "银行卡号开头6位不符合规范";
		// }

		int lastNum = Integer.parseInt(bankno.substring(bankno.length() - 1,
				bankno.length()));// 取出最后一位（与luhm进行比较）

		String first15Num = bankno.substring(0, bankno.length() - 1);// 前15或18位
		// System.out.println(first15Num);
		char[] newArr = new char[first15Num.length()]; // 倒叙装入newArr
		char[] tempArr = first15Num.toCharArray();
		for (int i = 0; i < tempArr.length; i++) {
			newArr[tempArr.length - 1 - i] = tempArr[i];
		}
		// System.out.println(newArr);

		int[] arrSingleNum = new int[newArr.length]; // 奇数位*2的积 <9
		int[] arrSingleNum2 = new int[newArr.length];// 奇数位*2的积 >9
		int[] arrDoubleNum = new int[newArr.length]; // 偶数位数组

		for (int j = 0; j < newArr.length; j++) {
			if ((j + 1) % 2 == 1) {// 奇数位
				if ((int) (newArr[j] - 48) * 2 < 9)
					arrSingleNum[j] = (int) (newArr[j] - 48) * 2;
				else
					arrSingleNum2[j] = (int) (newArr[j] - 48) * 2;
			} else
				// 偶数位
				arrDoubleNum[j] = (int) (newArr[j] - 48);
		}

		int[] arrSingleNumChild = new int[newArr.length]; // 奇数位*2 >9
															// 的分割之后的数组个位数
		int[] arrSingleNum2Child = new int[newArr.length];// 奇数位*2 >9
															// 的分割之后的数组十位数

		for (int h = 0; h < arrSingleNum2.length; h++) {
			arrSingleNumChild[h] = (arrSingleNum2[h]) % 10;
			arrSingleNum2Child[h] = (arrSingleNum2[h]) / 10;
		}

		int sumSingleNum = 0; // 奇数位*2 < 9 的数组之和
		int sumDoubleNum = 0; // 偶数位数组之和
		int sumSingleNumChild = 0; // 奇数位*2 >9 的分割之后的数组个位数之和
		int sumSingleNum2Child = 0; // 奇数位*2 >9 的分割之后的数组十位数之和
		int sumTotal = 0;
		for (int m = 0; m < arrSingleNum.length; m++) {
			sumSingleNum = sumSingleNum + arrSingleNum[m];
		}

		for (int n = 0; n < arrDoubleNum.length; n++) {
			sumDoubleNum = sumDoubleNum + arrDoubleNum[n];
		}

		for (int p = 0; p < arrSingleNumChild.length; p++) {
			sumSingleNumChild = sumSingleNumChild + arrSingleNumChild[p];
			sumSingleNum2Child = sumSingleNum2Child + arrSingleNum2Child[p];
		}

		sumTotal = sumSingleNum + sumDoubleNum + sumSingleNumChild
				+ sumSingleNum2Child;

		// 计算Luhm值
		int k = sumTotal % 10 == 0 ? 10 : sumTotal % 10;
		int luhm = 10 - k;

		if (lastNum == luhm) {
			return SUCCESS;// 验证通过
		} else {
			return ILLEGAL_NUMBER;
		}
	}

	/**
	 * 实现文本复制功能 add by wangqianzhou
	 * 
	 * @param content
	 */
	@SuppressLint("ShowToast")
	public void copy(String content, Context context) {
		ClipboardManager cmb = (ClipboardManager) context
				.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(content.trim());
		showToast("复制成功");
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		try {
			createVelocityTracker(event);
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				xDown = event.getRawX();
				yDown = event.getRawY();
				break;
			case MotionEvent.ACTION_MOVE:
				xMove = event.getRawX();
				yMove = event.getRawY();
				// 滑动的距离
				int distanceX = (int) (xMove - xDown);
				int distanceY = (int) (yMove - yDown);
				// 获取顺时速度
				int ySpeed = getScrollVelocity();
				// 关闭Activity需满足以下条件：
				// 1.x轴滑动的距离>XDISTANCE_MIN
				// 2.y轴滑动的距离在YDISTANCE_MIN范围内
				// 3.y轴上（即上下滑动的速度）<XSPEED_MIN，如果大于，则认为用户意图是在上下滑动而非左滑结束Activity
				if (distanceX > XDISTANCE_MIN
						&& (distanceY < YDISTANCE_MIN && distanceY > -YDISTANCE_MIN)
						&& ySpeed < YSPEED_MIN) {
					if (!(BaseActivity.this instanceof HomeActivity
							|| BaseActivity.this instanceof WelcomeActivity
							|| BaseActivity.this instanceof MyRegularDebtActivity
							|| BaseActivity.this instanceof DebtExchangeActivity
							|| BaseActivity.this instanceof MyDebtDetailActivity
							|| BaseActivity.this instanceof DebtSuccessActivity
							|| BaseActivity.this instanceof KKDWebActivity
							|| BaseActivity.this instanceof CalendarActivity
							|| BaseActivity.this instanceof TenderDetailActivity
							|| BaseActivity.this instanceof FinancialPlanParticularsActivity
							|| BaseActivity.this instanceof InformationActivity
							|| BaseActivity.this instanceof RegularParticularsActivity
							|| BaseActivity.this instanceof LivePlayerActivity
							|| BaseActivity.this instanceof ImageZoomActivity
							|| BaseActivity.this instanceof MyActivity || BaseActivity.this instanceof CreditorIsRightsParticularsActivity)) {
						finish();
					}
				}
				break;
			case MotionEvent.ACTION_UP:
				recycleVelocityTracker();
				break;
			default:
				break;
			}
			return super.dispatchTouchEvent(event);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	/**
	 * 创建VelocityTracker对象，并将触摸界面的滑动事件加入到VelocityTracker当中。
	 * 
	 * @param event
	 * 
	 */
	private void createVelocityTracker(MotionEvent event) {
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
	}

	/**
	 * 回收VelocityTracker对象。
	 */
	private void recycleVelocityTracker() {
		mVelocityTracker.recycle();
		mVelocityTracker = null;
	}

	/**
	 * 
	 * @return 滑动速度，以每秒钟移动了多少像素值为单位。
	 */
	private int getScrollVelocity() {
		mVelocityTracker.computeCurrentVelocity(1000);
		int velocity = (int) mVelocityTracker.getYVelocity();
		return Math.abs(velocity);
	}

	public void showToast(String hintLanguage) {
		// if (mToast != null) {
		// mToast.cancel();
		// mToast = null;
		// }
		// mToast = Toast.makeText(this, hintLanguage, Toast.LENGTH_SHORT);
		// mToast.setGravity(Gravity.CENTER, 0, 0);
		// mToast.show();
		AppUtil.makeToastForCustomer(this, hintLanguage);
	}

	public void showToast(int hintLanguage) {
		// if (mToast != null) {
		// mToast.cancel();
		// mToast = null;
		// }
		// mToast = Toast.makeText(this, hintLanguage, Toast.LENGTH_SHORT);
		// mToast.setGravity(Gravity.CENTER, 0, 0);
		// mToast.show();
		AppUtil.makeToastForCustomer(this, hintLanguage);
	}

	public void showToast(int hintLanguage, onToastDismiss callback) {

		AppUtil.makeToastForCustomer(this, hintLanguage, callback);
	}

	public void showToast(String hintLanguage, onToastDismiss callback) {

		AppUtil.makeToastForCustomer(this, hintLanguage, callback);
	}

	@Override
	protected void onDestroy() {
		BaseApplication.getInstance().removeActivity(this);
		super.onDestroy();
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		AppUtil.closeDialog();
		if (shareFailure != null) {
			shareFailure.cancel();
			shareFailure = null;
		}
		if (happyCoinCompleteProgressDialog != null) {
			happyCoinCompleteProgressDialog.cancel();
			happyCoinCompleteProgressDialog = null;
		}
		shareResult = -1;
	}

	Toast mToast;

	public void showToast2(String desc) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		View viewCustomer = LayoutInflater.from(this).inflate(
				R.layout.toast_item_dialog2, null);
		TextView tv_content = (TextView) viewCustomer
				.findViewById(R.id.tv_content);

		tv_content.setText(desc);
		mToast = new Toast(this);
		mToast.setGravity(Gravity.BOTTOM, 0, SystemUtils.dip2px(this, 50));
		mToast.setDuration(Toast.LENGTH_LONG);
		mToast.setView(viewCustomer);
		mToast.show();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sina.weibo.sdk.api.share.IWeiboHandler.Response#onResponse(com.sina
	 * .weibo.sdk.api.share.BaseResponse)
	 */
	@Override
	public void onResponse(BaseResponse baseResp) {
		if (baseResp != null) {
			switch (baseResp.errCode) {
			case WBConstants.ErrorCode.ERR_OK:
				shareResult = 0;
				// Toast.makeText(this, "分享成功", Toast.LENGTH_LONG).show();
				break;
			case WBConstants.ErrorCode.ERR_CANCEL:
				// Toast.makeText(this, "分享取消", Toast.LENGTH_LONG).show();
				shareResult = 1;
				break;
			case WBConstants.ErrorCode.ERR_FAIL:
				/*
				 * Toast.makeText(this, "分享失败" + "Error Message: " +
				 * baseResp.errMsg, Toast.LENGTH_LONG).show();
				 */
				shareResult = 1;
				break;
			}
		}
	}

	public void toShareURL(final Context activity,
			final String inviteFriendUrl, final String title,
			final String content, final String logo) {
		PreferenceUtils.getInstance().setH5Parameter(activity, inviteFriendUrl,
				title, content, logo);
		Dialog mDialog = DialogUtils.generateShareActDialog(activity,
				new ShareCallback() {

					@Override
					public void onShareToWxCycle() {
						// TODO Auto-generated method stub
						share2WX(activity, inviteFriendUrl, title, content,
								logo, false);
					}

					@Override
					public void onShareToWx() {
						// TODO Auto-generated method stub
						share2WX(activity, inviteFriendUrl, title, content,
								logo, true);
					}

					@Override
					public void onShareToSina() {
						// TODO Auto-generated method stub
						Intent intent = new Intent(activity,
								WeiboShareActivity.class);
						intent.putExtra("inviteFriendUrl", inviteFriendUrl);
						intent.putExtra("title", title);
						intent.putExtra("content", content);
						intent.putExtra("logoStr", logo);
						startActivity(intent);
						// ImageLoader.getInstance().loadImage(logo,
						// new ImageLoadingListener() {
						//
						// @Override
						// public void onLoadingStarted(
						// String imageUri, View view) {
						// // TODO Auto-generated method stub
						//
						// }
						//
						// @Override
						// public void onLoadingFailed(
						// String imageUri, View view,
						// FailReason failReason) {
						// // TODO Auto-generated method stub
						//
						// }
						//
						// @Override
						// public void onLoadingComplete(
						// String imageUri, View view,
						// Bitmap loadedImage) {
						// // TODO Auto-generated method stub
						// sendMessage(activity, inviteFriendUrl,
						// title, content, loadedImage);
						// }
						//
						// @Override
						// public void onLoadingCancelled(
						// String imageUri, View view) {
						// // TODO Auto-generated method stub
						//
						// }
						// });

					}

					@Override
					public void onShareToQzone() {
						// TODO Auto-generated method stub
						share2QQZone(activity, inviteFriendUrl, title, content,
								logo);
					}

					@Override
					public void onShareToQQ() {
						// TODO Auto-generated method stub
						share2QQ(activity, inviteFriendUrl, title, content,
								logo);
					}
				});
		mDialog.show();
	}

	/*
	 * 
	 * 
	 */
	public void toShareURL(final Context activity,
			final String inviteFriendUrl, final String title,
			final String content, final int logo) {
		boolean isLogin_share = inviteFriendUrl.indexOf("isLogin") > 0;
		if (isLogin_share) { // 说明分享链接需要户用信息

			if (PreferenceUtils.getInstance().getLogin(activity) == 0) { // 登录状态
				final Dialog mDialog = DialogUtils.generateShareActDialog(
						activity, new ShareCallback() {

							@Override
							public void onShareToWxCycle() {
								// TODO Auto-generated method stub
								share2WX(activity, inviteFriendUrl, title,
										content, logo, false);
							}

							@Override
							public void onShareToWx() {
								// TODO Auto-generated method stub
								share2WX(activity, inviteFriendUrl, title,
										content, logo, true);
							}

							@Override
							public void onShareToSina() {
								// TODO Auto-generated method stub

								// Bitmap bitmap = BitmapFactory.decodeResource(
								// activity.getResources(), logo);
								// 设置 Bitmap 类型的图片到视频对象里 设置缩略图。
								// 注意：最终压缩过的缩略图大小不得超过
								// 32kb。
								Intent intent = new Intent(activity,
										WeiboShareActivity.class);
								intent.putExtra("inviteFriendUrl",
										inviteFriendUrl);
								intent.putExtra("title", title);
								intent.putExtra("content", content);
								intent.putExtra("logoInt", logo);
								startActivity(intent);
								// sendMessage(activity, inviteFriendUrl, title,
								// content,
								// bitmap);
							}

							@Override
							public void onShareToQzone() {
								// TODO Auto-generated method stub
								String filePath = FileUtils.getKKDRootPath()
										+ (System.currentTimeMillis() + ".png");
								FileUtils.bitmapToFile(
										BitmapFactory.decodeResource(
												activity.getResources(), logo),
										filePath);
								share2QQZone(activity, inviteFriendUrl, title,
										content, filePath);
							}

							@Override
							public void onShareToQQ() {
								// TODO Auto-generated method stub
								String filePath = FileUtils.getKKDRootPath()
										+ (System.currentTimeMillis() + ".png");
								FileUtils.bitmapToFile(
										BitmapFactory.decodeResource(
												activity.getResources(), logo),
										filePath);
								share2QQPath(activity, inviteFriendUrl, title,
										content, filePath);
							}
						});
				mDialog.show();
			} else if (PreferenceUtils.getInstance().getLogin(activity) != 0) { // 未登录状态
				Intent intent = new Intent(activity, LoginActivity.class);
				startActivity(intent);
			}

		} else { // 说明分享链接不需要户用信息

			final Dialog mDialog = DialogUtils.generateShareActDialog(activity,
					new ShareCallback() {

						@Override
						public void onShareToWxCycle() {
							// TODO Auto-generated method stub
							share2WX(activity, inviteFriendUrl, title, content,
									logo, false);
						}

						@Override
						public void onShareToWx() {
							// TODO Auto-generated method stub
							share2WX(activity, inviteFriendUrl, title, content,
									logo, true);
						}

						@Override
						public void onShareToSina() {
							// TODO Auto-generated method stub

							// Bitmap bitmap = BitmapFactory.decodeResource(
							// activity.getResources(), logo);
							// 设置 Bitmap 类型的图片到视频对象里 设置缩略图。 注意：最终压缩过的缩略图大小不得超过
							// 32kb。
							Intent intent = new Intent(activity,
									WeiboShareActivity.class);
							intent.putExtra("inviteFriendUrl", inviteFriendUrl);
							intent.putExtra("title", title);
							intent.putExtra("content", content);
							intent.putExtra("logoInt", logo);
							startActivity(intent);
							// sendMessage(activity, inviteFriendUrl, title,
							// content,
							// bitmap);
						}

						@Override
						public void onShareToQzone() {
							// TODO Auto-generated method stub
							String filePath = FileUtils.getKKDRootPath()
									+ (System.currentTimeMillis() + ".png");
							FileUtils.bitmapToFile(
									BitmapFactory.decodeResource(
											activity.getResources(), logo),
									filePath);
							share2QQZone(activity, inviteFriendUrl, title,
									content, filePath);
						}

						@Override
						public void onShareToQQ() {
							// TODO Auto-generated method stub
							String filePath = FileUtils.getKKDRootPath()
									+ (System.currentTimeMillis() + ".png");
							FileUtils.bitmapToFile(
									BitmapFactory.decodeResource(
											activity.getResources(), logo),
									filePath);
							share2QQPath(activity, inviteFriendUrl, title,
									content, filePath);
						}
					});
			mDialog.show();
		}
	}

	protected static void share2WX(Context ctx, String inviteFriendUrl,
			String title, String content, int logo, boolean isWx) {

		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = inviteFriendUrl;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = title;
		msg.description = content;
		Bitmap thumb = BitmapFactory.decodeResource(ctx.getResources(), logo);
		// FileUtils.zoomBitmap(thumb, 200, 200);
		msg.thumbData = Util.bmpToByteArray(
				FileUtils.zoomBitmap(thumb, 200, 200), true);

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = isWx ? SendMessageToWX.Req.WXSceneSession
				: SendMessageToWX.Req.WXSceneTimeline;
		BaseApplication.getInstance().api.sendReq(req);

	}

	private static String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	protected static void share2WX(Context ctx, String inviteFriendUrl,
			String title, String content, String logo, final boolean isWx) {

		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = inviteFriendUrl;
		final WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = title;
		msg.description = content;
		ImageLoader.getInstance().loadImage(logo, new ImageLoadingListener() {

			@Override
			public void onLoadingStarted(String imageUri, View view) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap thumb) {
				// TODO Auto-generated method stub
				msg.thumbData = Util.bmpToByteArray(
						FileUtils.zoomBitmap(thumb, 100, 100), true);

				SendMessageToWX.Req req = new SendMessageToWX.Req();
				req.transaction = buildTransaction("webpage");
				req.message = msg;
				req.scene = isWx ? SendMessageToWX.Req.WXSceneSession
						: SendMessageToWX.Req.WXSceneTimeline;
				BaseApplication.getInstance().api.sendReq(req);
			}

			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void share2QQ(final Context ctx, String inviteFriendUrl,
			String title, String content, final String logo) {

		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, inviteFriendUrl);
		// params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, logo);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "快快贷");
		int mExtarFlag = 0x00;
		// mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN;
		// mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE;
		params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, mExtarFlag);
		ImageLoader.getInstance().loadImage(logo, new ImageLoadingListener() {

			@Override
			public void onLoadingStarted(String imageUri, View view) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap thumb) {

				params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,
						ImageLoader.getInstance().getDiskCache().get(logo)
								.getAbsolutePath());

				ThreadManager.getMainHandler().post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (null != BaseApplication.getInstance().mTencent)
							BaseApplication.getInstance().mTencent.shareToQQ(
									(Activity) ctx, params, qqShareListener);
					}
				});
			}

			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				// TODO Auto-generated method stub

			}
		});

		/*
		 * new Runnable() {
		 * 
		 * @Override public void run() { if (null != MainActivity.mTencent) {
		 * MainActivity.mTencent.shareToQQ(QQShareActivity.this, params,
		 * qqShareListener); } } }
		 */

	}

	public void share2QQPath(final Context ctx, String inviteFriendUrl,
			String title, String content, final String logo) {

		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, inviteFriendUrl);
		// params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, logo);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "快快贷");
		int mExtarFlag = 0x00;
		// mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN;
		// mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE;
		params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, mExtarFlag);
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, logo);

		ThreadManager.getMainHandler().post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (null != BaseApplication.getInstance().mTencent)
					BaseApplication.getInstance().mTencent.shareToQQ(
							(Activity) ctx, params, qqShareListener);
			}
		});

	}

	IUiListener qqShareListener = new IUiListener() {
		@Override
		public void onCancel() {
			if (shareType != QQShare.SHARE_TO_QQ_TYPE_IMAGE) {
				if (PreferenceUtils.getInstance()
						.getH5Entrance(BaseActivity.this).equals("邀请好友攻略")) {
					shareFailureDialog();
				}
				PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this,
						"");
				// Toast.makeText(BaseActivity.context.getApplicationContext(),
				// "分享取消", Toast.LENGTH_SHORT).show();
				// LogUtil.e("TAG", "onCancel--->");
			}
		}

		@Override
		public void onComplete(Object response) {
			if (PreferenceUtils.getInstance().getH5Entrance(BaseActivity.this)
					.equals("邀请好友攻略")) {
				addCoinMis();
			} else if (PreferenceUtils.getInstance()
					.getH5Entrance(BaseActivity.this).equals("视频分享")) {
				videoShareSuccess(); // 视频分享
			}
			PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this, "");
			// Toast.makeText(BaseActivity.context.getApplicationContext(),
			// "分享成功", Toast.LENGTH_SHORT).show();
			// LogUtil.e("TAG", "arg0-->" + response.toString());
		}

		@Override
		public void onError(UiError e) {
			if (PreferenceUtils.getInstance().getH5Entrance(BaseActivity.this)
					.equals("邀请好友攻略")) {
				shareFailureDialog();
			}
			PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this, "");
			// Toast.makeText(BaseActivity.context.getApplicationContext(),
			// "分享异常", Toast.LENGTH_SHORT).show();
			// LogUtil.e("TAG", "e.errorCode" + e.errorCode + ", msg:"
			// + e.errorMessage + ", detail:" + e.errorDetail);
		}
	};

	public void share2QQZone(final Context ctx, String inviteFriendUrl,
			String title, String content, String logo) {
		final Bundle params = new Bundle();
		params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
				QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
		params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, inviteFriendUrl);

		// 支持传多个imageUrl
		ArrayList<String> imageUrls = new ArrayList<String>();
		imageUrls.add(logo);
		params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);

		ThreadManager.getMainHandler().post(new Runnable() {

			@Override
			public void run() {
				if (null != BaseApplication.getInstance().mTencent) {
					BaseApplication.getInstance().mTencent.shareToQzone(
							(Activity) ctx, params, qZoneShareListener);
				}
			}
		});

	}

	IUiListener qZoneShareListener = new IUiListener() {

		@Override
		public void onCancel() {
			if (PreferenceUtils.getInstance().getH5Entrance(BaseActivity.this)
					.equals("邀请好友攻略")) {
				shareFailureDialog();
			}
			PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this, "");
			// Toast.makeText(BaseActivity.context.getApplicationContext(),
			// "分享取消", Toast.LENGTH_SHORT).show();
			// LogUtil.e("TAG", "qZone_onCancel--->");
		}

		@Override
		public void onComplete(Object response) {
			if (PreferenceUtils.getInstance().getH5Entrance(BaseActivity.this)
					.equals("邀请好友攻略")) {
				addCoinMis();
			} else if (PreferenceUtils.getInstance()
					.getH5Entrance(BaseActivity.this).equals("视频分享")) {
				videoShareSuccess(); // 视频分享
			}
			PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this, "");
			// Toast.makeText(BaseActivity.context.getApplicationContext(),
			// "分享成功", Toast.LENGTH_SHORT).show();
			// LogUtil.e("TAG", "qZone_arg0-->" + response.toString());
			// PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this,
			// "");
		}

		@Override
		public void onError(UiError e) {
			if (PreferenceUtils
					.getInstance()
					.getH5Entrance(BaseActivity.context.getApplicationContext())
					.equals("邀请好友攻略")) {
				shareFailureDialog();
			}
			PreferenceUtils.getInstance().setH5Entrance(BaseActivity.this, "");
			// Toast.makeText(BaseActivity.context.getApplicationContext(),
			// "分享异常", Toast.LENGTH_SHORT).show();
			// LogUtil.e("TAG", "qZone_e.errorCode" + e.errorCode + ", msg:"
			// + e.errorMessage + ", detail:" + e.errorDetail);
		}
	};

	public boolean IsHasSina(Context mContext) {
		boolean mIsHasQQ = false;
		// 通过查询，获得所有ResolveInfo对象.
		// PackageManager pm = mContext.getPackageManager();
		// Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		// mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		// List<ResolveInfo> resolveInfos = pm
		// .queryIntentActivities(mainIntent, 0);
		// for (ResolveInfo i : resolveInfos) {
		// if (i.activityInfo.packageName.contains("com.sina.weibo")) {
		// mIsHasQQ = true;
		// }
		// }
		mIsHasQQ = mWeiboShareAPI.isWeiboAppInstalled();
		return mIsHasQQ;
	}

	public static final int SHARE_CLIENT = 1;
	public static final int SHARE_ALL_IN_ONE = 2;

	public static void shareWeiBo(Context ctx, String inviteFriendUrl,
			String title, String content, Bitmap logo) {

		WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
		// ImageObject imageObject = new ImageObject();
		// imageObject.setImageObject(logo);
		// weiboMessage.imageObject = imageObject;
		TextObject textObject = new TextObject();
		textObject.title = title;
		textObject.text = content;
		weiboMessage.textObject = textObject;
		WebpageObject mediaObject = new WebpageObject();
		mediaObject.identify = Utility.generateGUID();
		// mediaObject.title = title;
		// mediaObject.description =content;

		// mediaObject.setThumbImage(logo);
		mediaObject.actionUrl = inviteFriendUrl;
		// mediaObject.defaultText = content;
		weiboMessage.mediaObject = mediaObject;
		// 2. 初始化从第三方到微博的消息请求
		SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
		// 用transaction唯一标识一个请求
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.multiMessage = weiboMessage;

		// 3. 发送请求消息到微博，唤起微博分享界面
		// if (IsHasSina(ctx)) {
		// ((BaseActivity)ctx).mWeiboShareAPI.sendRequest((BaseActivity) ctx,
		// request);
		// }else{
		AuthInfo authInfo = new AuthInfo(ctx, SinaConstants.APP_KEY,
				SinaConstants.REDIRECT_URL, SinaConstants.SCOPE);
		Oauth2AccessToken accessToken = AccessTokenKeeper
				.readAccessToken(BaseApplication.getInstance());
		String token = "";
		if (accessToken != null) {
			token = accessToken.getToken();
		}
		((BaseActivity) ctx).mWeiboShareAPI.sendRequest((BaseActivity) ctx,
				request, authInfo, token, new WeiboAuthListener() {

					@Override
					public void onWeiboException(WeiboException arg0) {
						arg0.printStackTrace();
					}

					@Override
					public void onComplete(Bundle bundle) {
						// TODO Auto-generated method stub
						Oauth2AccessToken newToken = Oauth2AccessToken
								.parseAccessToken(bundle);
						AccessTokenKeeper.writeAccessToken(
								BaseApplication.getInstance(), newToken);
						Toast.makeText(
								BaseApplication.getInstance(),
								"onAuthorizeComplete token = "
										+ newToken.getToken(), 0).show();
					}

					@Override
					public void onCancel() {
					}
				});
	}

	/**
	 * 第三方应用发送请求消息到微博，唤起微博分享界面。
	 * 
	 * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage}
	 */
	public void sendMessage(Context mContext, String inviteFriendUrl,
			String title, String content, Bitmap logo) {
		if (IsHasSina(mContext)) {
			if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
				int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
				if (supportApi >= 10351 /* ApiUtils.BUILD_INT_VER_2_2 */) {
					sendMultiMessage(mContext, inviteFriendUrl, title, content,
							logo);
				} else {
					sendSingleMessage(mContext, inviteFriendUrl, title,
							content, logo);
				}
			} else {
				Toast.makeText(mContext,
						"微博客户端不支持 SDK 分享或微博客户端未安装或微博客户端是非官方版本。",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			sendMultiMessage(mContext, inviteFriendUrl, title, content, logo);
		}
	}

	/**
	 * 第三方应用发送请求消息到微博，唤起微博分享界面。 注意：当
	 * {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时，支持同时分享多条消息，
	 * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
	 * 
	 * @param hasText
	 *            分享的内容是否有文本
	 * @param hasImage
	 *            分享的内容是否有图片
	 * @param hasWebpage
	 *            分享的内容是否有网页
	 * @param hasMusic
	 *            分享的内容是否有音乐
	 * @param hasVideo
	 *            分享的内容是否有视频
	 * @param hasVoice
	 *            分享的内容是否有声音
	 */
	private void sendMultiMessage(final Context mContext,
			String inviteFriendUrl, String title, String content, Bitmap logo) {

		// 1. 初始化微博的分享消息
		WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
		// if(mWeiboShareAPI.isWeiboAppInstalled()){

		// 链接
		// WebpageObject mediaObject = new WebpageObject();
		// mediaObject.actionUrl = inviteFriendUrl;
		// // mediaObject.defaultText = "["+title+"]"+content;
		// // mediaObject.setThumbImage(FileUtils.zoomBitmap(logo, 100, 100));
		// weiboMessage.mediaObject = mediaObject;
		TextObject textObject = new TextObject();
		textObject.title = title;
		textObject.text = "[" + title + "]:" + content + inviteFriendUrl;
		weiboMessage.textObject = textObject;
		// }else{
		// //文本
		// TextObject textObject = new TextObject();
		// textObject.title = title;
		// textObject.text = content;
		// weiboMessage.textObject = textObject;
		// //logo
		// ImageObject imageObject = new ImageObject();
		// imageObject.setImageObject(FileUtils.zoomBitmap(logo, 100, 100));
		// weiboMessage.imageObject = imageObject;
		// //链接
		// WebpageObject mediaObject = new WebpageObject();
		// mediaObject.actionUrl = inviteFriendUrl;
		// weiboMessage.mediaObject = mediaObject;
		// }

		// 2. 初始化从第三方到微博的消息请求
		SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
		// 用transaction唯一标识一个请求
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.multiMessage = weiboMessage;

		// 3. 发送请求消息到微博，唤起微博分享界面
		if (IsHasSina(mContext)) {
			mWeiboShareAPI.sendRequest((BaseActivity) mContext, request);
		} else {
			AuthInfo authInfo = new AuthInfo(mContext, SinaConstants.APP_KEY,
					SinaConstants.REDIRECT_URL, SinaConstants.SCOPE);
			Oauth2AccessToken accessToken = AccessTokenKeeper
					.readAccessToken(mContext.getApplicationContext());
			String token = "";
			if (accessToken != null) {
				token = accessToken.getToken();
			}
			mWeiboShareAPI.sendRequest((BaseActivity) mContext, request,
					authInfo, token, new WeiboAuthListener() {

						@Override
						public void onWeiboException(WeiboException arg0) {
							arg0.printStackTrace();
						}

						@Override
						public void onComplete(Bundle bundle) {
							// TODO Auto-generated method stub
							// Oauth2AccessToken newToken =
							// Oauth2AccessToken.parseAccessToken(bundle);
							// AccessTokenKeeper.writeAccessToken(mContext.getApplicationContext(),
							// newToken);
							// Toast.makeText(mContext.getApplicationContext(),
							// "onAuthorizeComplete token = " +
							// newToken.getToken(), 0).show();
						}

						@Override
						public void onCancel() {
						}
					});
		}
	}

	private void sendSingleMessage(Context mContext, String inviteFriendUrl,
			String title, String content, Bitmap logo) {

		// 1. 初始化微博的分享消息
		// 用户可以分享文本、图片、网页、音乐、视频中的一种
		WeiboMessage weiboMessage = new WeiboMessage();
		WebpageObject mediaObject = new WebpageObject();
		mediaObject.identify = Utility.generateGUID();
		mediaObject.title = title;
		mediaObject.description = content;

		mediaObject.setThumbImage(FileUtils.zoomBitmap(logo, 100, 100));
		mediaObject.actionUrl = inviteFriendUrl;
		mediaObject.defaultText = content;
		weiboMessage.mediaObject = mediaObject;
		/*
		 * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
		 */

		// 2. 初始化从第三方到微博的消息请求
		SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
		// 用transaction唯一标识一个请求
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.message = weiboMessage;

		// 3. 发送请求消息到微博，唤起微博分享界面
		mWeiboShareAPI.sendRequest(((BaseActivity) mContext), request);
	}

	/****
	 * 分享失败Dialog
	 ****/
	public void shareFailureDialog() {

		if (shareFailure != null) {
			shareFailure.cancel();
			shareFailure = null;
		}
		shareFailure = DialogUtils.communalDialog(this, new OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.cancel_tv_bt: // 取消
					shareFailure.dismiss();
					PreferenceUtils.getInstance().clearSharePrefernces(
							BaseActivity.this);
					break;
				case R.id.re_share_bt: // 重新分享
					shareFailure.dismiss();
					String all = PreferenceUtils.getInstance().getH5Parameter(
							BaseActivity.this);
					if (!TextUtils.isEmpty(all)) {
						String[] stList = all.split("&");
						PreferenceUtils.getInstance().setH5Entrance(
								BaseActivity.this, "邀请好友攻略");
						toShareURL(BaseActivity.this, stList[0], stList[1],
								stList[2], stList[3]);
					}
					break;
				}

			}
		});
		shareFailure.show();

	}

	/**********
	 * 分享邀请好友接口
	 **********/
	public void addCoinMis() {
		LogUtil.e("TAG", "成功：" + System.currentTimeMillis());
		String custmeridAndToken = PreferenceUtils.getInstance().getcustomerId(
				this);
		String[] cat = custmeridAndToken.split("&");
		if (cat == null || cat.length < 2)
			return;
		KkdHttpMagager.getInstance().addCoinMis(Share.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						shareData = (Share) responseBody;
						mHandler.sendEmptyMessage(SHARE_CODE_ZERO);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						mHandler.sendEmptyMessage(SHARE_CODE_ELSE);
					}
				});
	}

	/***********
	 * 快乐币任务完成进度Dialog
	 ***********/
	public void happyCoinCompleteProgressDialog(int signInStatus,
			int signInCionSum, long signIncouponAmount, int signDays, int type,
			int inviteCionSum, int inviteStatus, int poiStatus, int poiCionSum,
			int poiMoreCionSum, String inviteStrategyUrl, int doubleAllSum,
			int customerSeat, int doubleSum, String doubleRate,
			int doubleMisSum, String coinMisUrl, int isRepairSigninStatus) {
		if (happyCoinCompleteProgressDialog != null) {
			happyCoinCompleteProgressDialog.cancel();
			happyCoinCompleteProgressDialog = null;
		}
		happyCoinCompleteProgressDialog = DialogUtils
				.happyCoinCompleteProgressDialog(this, false, signInStatus,
						signInCionSum, signIncouponAmount, signDays, type,
						inviteCionSum, inviteStatus, poiStatus, poiCionSum,
						poiMoreCionSum, inviteStrategyUrl, doubleAllSum,
						customerSeat, doubleSum, doubleRate, doubleMisSum,
						coinMisUrl, isRepairSigninStatus);
		try {
			happyCoinCompleteProgressDialog.show();
		} catch (Exception e) {
			// 忽略
		}

	}

	/**********
	 * 视频分享成功
	 **********/
	public void videoShareSuccess() {
		// Processed by LiveHomeActivity and LivePlayerActivity subclasses;
	}

}
